// pages/publish/publish.js
import dayjs from 'dayjs';

import {
  domain,
  http
} from '@/utils/request'

import {
  uploadFiles
} from '@/utils/util'

function omit(obj, props) {
  const result = {};
  for (const key in obj) {
    if (props.indexOf(key) === -1) {
      result[key] = obj[key];
    }
  }
  return result;
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isEdit: false,
    isAudit: false,
    mode: '',
    datetimeVisible: false,
    datetimeVisible11: false,
    datetimeVisible22: false,
    datetime: dayjs().valueOf(),
    statusOptions: [{
        value: 0,
        label: '待审核',
        type: 'info'
      },
      {
        value: 1,
        label: '审核成功',
        type: 'success'
      },
      {
        value: 2,
        label: '审核失败',
        type: 'error'
      },
    ],
    statusMap: {
      0: '待审核',
      1: '审核成功',
      2: '审核失败',
    },
    gridConfig: {
      width: 218,
      height: 218,
      column: 2,
    },
    imageProps: {
      mode: 'aspectFit',
    },
    uploadFiles: [],
    name: '',
    detail: '',
    number: 1,
    originalPrice: '',
    status: 0,
    goodsUnit: '',
    unit: '',
    startingBid: '',
    whAddress: '',
    delayedPeriod: '',
    auctionGradient: '',
    bond: '',
    minCount: '',
    prdLocation: '',
    spec: '',
    purity: '',
    taxRate: '',
    registrationFee: '',
    reservePrice: true,
    serviceFeeRatio: '',
    auctionStartTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    auctionEndTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    effectiveTime: dayjs().add(1, 'month').format('YYYY-MM-DD'),
    statusVisible: false,
    hasChange: false,
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().init();
    wx.setNavigationBarTitle({
      title: '竞拍申请',
    });
  },

  async fetchGoodsDetail() {
    const goodsId = wx.getStorageSync('goodsId')
    const res = await http('POST', '/goods/detail', {
      id: goodsId
    })
    this.setData({
      name: res.name,
      detail: res.detail,
      originalPrice: res.originalPrice,
      effectiveTime: res.effectiveTime,
      number: res.number,
      goodsUnit: res.goodsUnit,
      unit: res.unit,
      startingBid: res.startingBid,
      whAddress: res.whAddress,
      delayedPeriod: res.delayedPeriod,
      auctionGradient: res.auctionGradient,
      bond: res.bond,
      minCount: res.minCount,
      prdLocation: res.prdLocation,
      spec: res.spec,
      purity: res.purity,
      taxRate: res.taxRate,
      registrationFee: res.registrationFee,
      reservePrice: res.reservePrice,
      serviceFeeRatio: res.serviceFeeRatio,
      auctionStartTime: res.auctionStartTime,
      auctionEndTime: res.auctionEndTime,
      uploadFiles: res.imgUrl.split(',').map(i => ({
        url: i,
        name: i
      }))
    })
  },

  handleRemove() {
    this.setData({
      uploadFiles: []
    })
  },

  hasChange() {
    this.setData({
      hasChange: true
    })
  },

  async formSubmit() {
    const {
      name,
      detail,
      number,
      originalPrice,
      status,
      effectiveTime,
      goodsUnit,
      unit,
      whAddress,
      delayedPeriod,
      auctionGradient,
      bond,
      minCount,
      prdLocation,
      spec,
      startingBid,
      purity,
      taxRate,
      registrationFee,
      reservePrice,
      serviceFeeRatio,
      auctionStartTime,
      auctionEndTime,
    } = this.data
    const {
      id
    } = wx.getStorageSync('userInfo')
    const goodsId = wx.getStorageSync('goodsId')
    const data = {
      userId: id,
      id: goodsId,
      name,
      detail,
      number,
      originalPrice,
      status,
      effectiveTime,
      goodsUnit,
      unit,
      whAddress,
      delayedPeriod,
      auctionGradient,
      bond,
      startingBid,
      minCount: Number(minCount),
      prdLocation,
      spec,
      purity,
      taxRate,
      registrationFee,
      reservePrice,
      serviceFeeRatio,
      auctionStartTime,
      auctionEndTime,
      imgUrl: this.data.uploadFiles.map(i => i.url).join(',')
    }

    await http('POST', '/goods/add', data)

    this.setData({
      uploadFiles: [],
      name: '',
      detail: '',
      number: 1,
      originalPrice: '',
      status: 0,
      goodsUnit: '',
      unit: '',
      startingBid: '',
      whAddress: '',
      delayedPeriod: '',
      auctionGradient: '',
      bond: '',
      minCount: '',
      prdLocation: '',
      spec: '',
      purity: '',
      taxRate: '',
      registrationFee: '',
      reservePrice: true,
      serviceFeeRatio: '',
      auctionStartTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      auctionEndTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      effectiveTime: dayjs().add(1, 'month').format('YYYY-MM-DD'),
    })

    wx.showToast({
      title: '发布成功',
    })
  },

  onPickerChange(e) {
    const {
      value
    } = e.detail;
    this.setData({
      statusVisible: false,
      status: value[0],
    });
  },

  onPickerCancel() {
    this.setData({
      statusVisible: false,
    });
  },

  showPicker() {
    this.setData({
      datetimeVisible: true,
    });
  },
  hidePicker() {
    this.setData({
      datetimeVisible: false,
    });
  },

  showPicker11() {
    this.setData({
      datetimeVisible11: true,
    });
  },
  hidePicker11() {
    this.setData({
      datetimeVisible11: false,
    });
  },
  showPicker22() {
    this.setData({
      datetimeVisible22: true,
    });
  },
  hidePicker22() {
    this.setData({
      datetimeVisible22: false,
    });
  },

  onCityPicker() {
    if (!this.data.isView) {
      this.setData({
        statusVisible: true
      });
    }
  },
  onConfirm(e) {
    const {
      value
    } = e?.detail;

    this.setData({
      effectiveTime: value,
    });

    this.hidePicker();
  },

  async handleSuccess(e) {
    console.log(e)
    const uploadedFiles = []
    const results = await uploadFiles(e.detail.files.reduce((acc, cur) => (cur.url?.includes('/tmp/') && acc.push(cur.url), acc), []))
    console.log('results', results)
    for (const result of results) {
      if (result.status === 'fulfilled') {
        uploadedFiles.push({
          name: 'image',
          url: result.value.value
        })
      }
    }
    this.setData({
      uploadFiles: [...this.data.uploadFiles, ...uploadedFiles]
    })
  },
  stepperchange(e) {
    this.setData({
      number: e.detail.value
    })
  },
  switchChange(e) {
    this.setData({
      reservePrice: e.detail.value
    })
  },
  onConfirm11(e) {
    const {
      value
    } = e?.detail;

    this.setData({
      auctionStartTime: value,
    });

    this.hidePicker();
  },
  onConfirm22(e) {
    const {
      value
    } = e?.detail;

    this.setData({
      auctionEndTime: value,
    });

    this.hidePicker();
  },
});